package net.tarine.oracolo.server.service;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.tarine.oracolo.client.service.AuthService;
import net.tarine.oracolo.server.persistence.PMF;
import net.tarine.oracolo.shared.model.Account;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class AuthServiceImpl extends RemoteServiceServlet implements
		AuthService {

	@Override
	public Account getAccountByToken(String token)
			throws IllegalArgumentException {
		Account result = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = null;
        try {
			q = pm.newQuery(Account.class);
			q.setFilter("token == tokenParam");
			q.declareParameters("String tokenParam");
			@SuppressWarnings("unchecked")
			List<Account> results = (List<Account>) q.execute(token);
			if (!results.isEmpty()) {
				result = pm.detachCopy(results.get(0));
			}
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		} finally {
			if (q != null) q.closeAll();
	        pm.close();
	    }
		return result;
	}

	@Override
	public Account saveOrUpdateAccount(Account account) throws IllegalArgumentException {
		Account result = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
        	result = pm.makePersistent(account);
            result = pm.detachCopy(result);
        } catch (Exception e) {
			throw new IllegalArgumentException(e);
		} finally {
            pm.close();
        }
        return result;
	}

	@Override
	public Boolean removeAccount(Account account)
			throws IllegalArgumentException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.deletePersistent(account);
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		} finally {
            pm.close();
        }
		return true;
	}

}
